package com.atguigu.gmall.mq.controller;

import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.service.RabbitService;
import com.atguigu.gmall.mq.config.DeadLetterMqConfig;
import com.atguigu.gmall.mq.config.DelayedMqConfig;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author mqx
 * 消息的发送者
 * @date 2020-8-11 14:24:48
 */
@RestController
@RequestMapping("mq")
public class MqController {

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 制作一个映射路径
    @GetMapping("sendConfirm")
    public Result sendConfirm(){
        // 获取一个当前系统时间
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        rabbitService.sendMessage("exchange.confirm","routing.confirm666",sf.format(new Date()));
        return Result.ok();
    }

    // 发送延迟队列
    @GetMapping("sendDeadLettle")
    public Result sendDeadLettle(){
        // 发送消息 在队列中设置了一个过期时间 10秒钟 ，
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // rabbitService.sendMessage("exchange.confirm","routing.confirm666",sf.format(new Date()));
        rabbitTemplate.convertAndSend(DeadLetterMqConfig.exchange_dead,DeadLetterMqConfig.routing_dead_1,"ok");
        // 什么时候发送的消息
        System.out.println(sf.format(new Date())+ "发送消息了。。。。");
        return Result.ok();
    }

    @GetMapping("sendDelay")
    public Result sendDelay(){
        // 制作时间的格式，
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 发送消息时，自定义一个消息的TTL
        rabbitTemplate.convertAndSend(DelayedMqConfig.exchange_delay, DelayedMqConfig.routing_delay,
                "ok", new MessagePostProcessor() {
                    @Override
                    public Message postProcessMessage(Message message) throws AmqpException {

                        // 设置一个消息的返回时间 10 秒钟
                        message.getMessageProperties().setDelay(10*1000);
                        System.out.println(sf.format(new Date())+ "发送消息了。。。。");
                        return message;
                    }
                });

        return Result.ok();
    }
}
